#include <vector>
using std::vector;

class Solution {
public:
    bool check(vector<int> &nums, int x, int m) {
        int sum = 0;
        int cnt = 1;
        for (int i = 0; i < nums.size(); i++) {
            if (sum + nums[i] > x) {
                cnt++;
                sum = nums[i];
            } else {
                sum += nums[i];
            }
        }
        return cnt <= m;
    }

    int splitArray(vector<int>& nums, int m) {
        int left = 0;
        int right = 0;
        for (int i = 0; i < nums.size(); i++) {
            right += nums[i];
            if (left < nums[i])
                left = nums[i];
        }

        while (left < right) {
            int mid = left + (right - left) / 2;
            if (check(nums, mid, m))
                right = mid;
            else
                left = mid + 1;
        }
        return left;
    }
};